import { Component, ReactNode } from "react";
import BoilingVerdict from "./BoilinvVerdict";
import TemperatureInput from "./TemperatureInput";
import tryConvert from "./utils";

// 约束state类型
type Istate = {
    temperature: string
    scale: string
}

// 声明接口约束类
interface Cal {
    handelChange: (e: any) => void;
    handleCelsiusChange: (t: string) => void
    handleFahrenheitChange: (t: string) => void

}
class Calculator extends Component<any, Istate> implements Cal {
    state = {
        temperature: '',
        scale: 'c'
    }

    // 组件受控
    handelChange = (e: any) => {
        console.log(e.target.value)
        this.setState({
            temperature: e.target.value
        })
    }
    // 摄氏度变化
    handleCelsiusChange = (temperature: string) => {
        console.log(temperature);
        this.setState({
            temperature,
            scale: 'c'
        })
    }

    // 华氏度变化
    handleFahrenheitChange = (temperature: string) => {
        console.log(temperature);
        this.setState({
            temperature,
            scale: 'f'
        })
    }
    render(): ReactNode {
        // 解构temperature scale属性
        let { temperature, scale } = this.state

        // 计算摄氏度
        let celsius = scale === 'c' ? temperature : tryConvert(temperature, 'toCelsius')
        // 计算华氏度
        let fahrenheit = scale === 'f' ? temperature : tryConvert(temperature, 'toFahrenheit')
        return (
            <fieldset>
                <legend>Calculator</legend>

                {/* 摄氏度输入框 */}
                <TemperatureInput scale='c' onTemperatureChange={this.handleCelsiusChange} temperature={celsius} />

                {/* 华氏度输入框 */}
                <TemperatureInput scale='f' onTemperatureChange={this.handleFahrenheitChange} temperature={fahrenheit} />

                {/* 温度验证 */}
                <BoilingVerdict temperature={celsius} />
            </fieldset>
        )
    }
}

export default Calculator